package com.lzw.blog.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzw.blog.admin.mapper.ArticleMapper;
import com.lzw.blog.admin.mapper.CommentMapper;
import com.lzw.blog.admin.mapper.UserMapper;
import com.lzw.blog.admin.mapper.UserRoleMspper;
import com.lzw.blog.admin.model.params.PageCount;
import com.lzw.blog.admin.model.params.PageParam;
import com.lzw.blog.admin.pojo.*;

import com.lzw.blog.admin.vo.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMspper userRoleMspper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private PermissionService permissionService;

    public User findUserById(Long authorId) {
        User user = userMapper.selectById(authorId);
        if (user == null) {
            user = new User();
            user.setNickname("vite");
        }
        return user;
    }

    public User findUser(String account, String password) {
        //查询条件,根据用户名和加密后的密码来进行判断
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account);
        queryWrapper.eq(User::getPassword, password);
        queryWrapper.select(User::getId, User::getAccount, User::getAvatar, User::getNickname);
        //提高查询效率
        queryWrapper.last("limit 1");
        return userMapper.selectOne(queryWrapper);
    }

    public User findUserByAccount(String account) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account);
        queryWrapper.last("limit 1");
        return userMapper.selectOne(queryWrapper);
    }
    public User findUserByEmail(String email) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email);
        queryWrapper.last("limit 1");
        return userMapper.selectOne(queryWrapper);
    }

    public User findUserByResetToken(String resetToken) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User:: getResetToken, resetToken);
        queryWrapper.last("limit 1");
        return userMapper.selectOne(queryWrapper);
    }

    public Result listUser(PageParam pageParam) {
        Page<User> page = new Page<>(pageParam.getCurrentPage(), pageParam.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pageParam.getQueryString())) {
            queryWrapper.like(User::getAccount, pageParam.getQueryString());
        }
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);

        PageResult<UserVo> pageResult = new PageResult<>();

        pageResult.setList(copyList(userPage.getRecords()));
        pageResult.setTotal(userPage.getTotal());

        return Result.success(pageResult);
    }

    public List<UserVo> copyList(List<User> userList) {
        List<UserVo> userVoList = new ArrayList<>();
        for (User user : userList) {

            UserVo userVo = new UserVo();
            userVo.setUser(user);
            LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserRole::getUserId, user.getId());

            UserRole userRole = userRoleMspper.selectOne(lambdaQueryWrapper);
            userVo.setRole(roleService.findRoleById(userRole.getRoleId()));

            Long createDate = user.getCreateDate();
            long milliseconds = createDate * 1000; // 将秒级时间戳转换为毫秒级时间戳

            DateTime dateTime = new DateTime(milliseconds);
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
            String formattedDateTime = dateTime.toString(formatter);
            userVo.setCreateDate(formattedDateTime);

            userVoList.add(userVo);
        }
        return userVoList;
    }


    public Result setRoleForUser(Long userId, Long roleId) {
        UpdateWrapper<UserRole> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("role_id", roleId).eq("user_id", userId);
        int updateCount = userRoleMspper.update(null, updateWrapper);
        return Result.success("修改成功");
    }


    public Result add(User user) {
        String pwd = DigestUtils.md5Hex(user.getPassword() + "liuzhiwei");
        user.setPassword(pwd);
        userMapper.insert(user);
        return Result.success(null);
    }

    public Result update(User user) {
        String pwd = DigestUtils.md5Hex(user.getPassword() + "liuzhiwei");
        user.setPassword(pwd);
        userMapper.updateById(user);
        return Result.success(null);
    }

    public Result updateResetToken(User user) {
        userMapper.updateById(user);
        return Result.success(null);
    }

    public Result delete(Long id) {
        // 删除对应角色
        LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRole::getUserId, id);
        userRoleMspper.delete(lambdaQueryWrapper);

        // 删除对应文章
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleLambdaQueryWrapper.eq(Article::getAuthorId, id);
        articleMapper.delete(articleLambdaQueryWrapper);

        // 删除对应评论
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(Comment::getAuthorId, id);
        commentMapper.delete(commentLambdaQueryWrapper);

        userMapper.deleteById(id);
        return Result.success(null);
    }


    public List<Permission> findPermissionByUserId(Long userId) {
        LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRole::getUserId, userId);
        UserRole userRole = userRoleMspper.selectOne(lambdaQueryWrapper);
        return permissionService.findPermissionsByRoleId(userRole.getRoleId());
    }

    public Result getNums() {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        PageCount pageCount = new PageCount();
        pageCount.setCount(userMapper.selectCount(lambdaQueryWrapper));

        return Result.success(pageCount);
    }

    /**
     * 返回最新注册用户
     * @param limit
     * @return
     */
    public Result newUsers(int limit) {
        //最新用户
        //查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(User::getCreateDate);
        queryWrapper.last("limit " + limit);

        List<User> userList = userMapper.selectList(queryWrapper);
        List<UserVo> userVoList = copyList(userList);

        return Result.success(userVoList);
    }
}
